using SixLabors.Fonts;
using Vin.Extension.Captcha.Options;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.EnvironmentCategory;

namespace Vin.Extension.Captcha.Tools;

public class VinFonts
{
    public static List<FontFamily> Families => SystemFonts.Families.Concat(_customFonts).ToList();

    private static List<FontFamily> _customFonts = new List<FontFamily>();
    private static FontCollection _fontCollection = new FontCollection();

    public static void LoadCustomFontsAsync()
    {
        var fontOption = VinApp.GetConfig<VinFontsOption>();
        if (fontOption.CustomFonts == null || !fontOption.CustomFonts.Any()) return;
        foreach (var fontPath in fontOption.CustomFonts)
        {
            var allPath = EnvironmentTool.GetRelativeProcessDirectory(fontPath);
            // Console.WriteLine("Loading custom font " + fontPath + " from: " + allPath + ",exists:" +
            //                   File.Exists(allPath));
            if (string.IsNullOrEmpty(allPath) || !File.Exists(allPath)) continue;

            try
            {
                _customFonts.Add(_fontCollection.Add(allPath));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error loading font from {fontPath}: {ex.Message}");
            }
        }
    }

    public static Font CreateFont(string familyName, float size, FontStyle style = FontStyle.Regular)
    {
        var fontFamily = Families.FirstOrDefault(f => f.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase));
        if (string.IsNullOrEmpty(fontFamily.Name))
            throw new ArgumentException($"Font family '{familyName}' not found.");
        return fontFamily.CreateFont(size, style);
    }
}